package com.framework.mybatis.plugin;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.Plugin;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.internal.util.StringUtility;

import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author LeeJun
 * @version 2.0.0
 * @time 2017-8-11 16:49
 */
public class FieldNameConvertPlugin extends PluginAdapter {

	private boolean smallCamel = true;

	@Override
	public void setProperties(Properties properties) {
		super.setProperties(properties);
		String camelStr = properties.getProperty("smallCamel");
		if (camelStr != null && !camelStr.equals("")) {
			this.smallCamel = StringUtility.isTrue(properties.getProperty("smallCamel"));
		}
	}

	@Override
	public boolean validate(List<String> warnings) {
		return true;
	}

	@Override
	public boolean modelFieldGenerated(Field field,
									   TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn,
									   IntrospectedTable introspectedTable,
									   Plugin.ModelClassType modelClassType) {

		this.convertFieldName(field, introspectedColumn);
		return true;
	}

	/**
	 * 转换字段名称为驼峰规则
	 *
	 * @author LeeJun
	 * @time 2017-8-11 16:56
	 * @version 2.0.0
	 */
	protected void convertFieldName(Field field, IntrospectedColumn introspectedColumn) {
		String fieldName = this.underlineToCamelHump(introspectedColumn.getActualColumnName()).replace("_", "");
		introspectedColumn.setJavaProperty(fieldName);
		field.setName(fieldName);
	}

	/**
	 * 将下划线风格替换为驼峰风格
	 *
	 * @author LeeJun
	 * @time 2017-8-11 17:00
	 * @version 2.0.0
	 */
	public static String underlineToCamelHump(String str) {
		Matcher matcher = Pattern.compile("_[a-z]").matcher(str);
		StringBuilder builder = new StringBuilder(str);
		for (int i = 0; matcher.find(); i++) {
			builder.replace(matcher.start() - i, matcher.end() - i, matcher.group().substring(1).toUpperCase());
		}
		if (Character.isUpperCase(builder.charAt(0))) {
			builder.replace(0, 1, String.valueOf(Character.toLowerCase(builder.charAt(0))));
		}
		return builder.toString();
	}

}
